package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.*;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.vo.ExportProductResult;
import cn.itcast.vo.ExportResult;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service
public class ExportServiceImpl implements ExportService{

    @Autowired
    private ExportDao exportDao;
    @Autowired
    private ContractDao contractDao;
    @Autowired
    private ContractProductDao contractProductDao; //合同货物dao
    @Autowired
    private ExportProductDao exportProductDao; //报运单商品dao
    @Autowired
    private ExtCproductDao extCproductDao; //合同附件dao
    @Autowired
    private ExtEproductDao extEproductDao;  //报运单附件dao


   //保存出口报运

    /**
     * export对象：
     *      contractIds : 所有勾选的合同id （以" ," 隔开）
     */
    public void save(Export export) {
        //I、保存报运单
        //1.设置报运单id
        export.setId(UUID.randomUUID().toString());
        //2.获取已勾选的合同id 字符串: 把字符串按照 "," 分离
        String contractIds = export.getContractIds();
        String [] ids = contractIds.split(",");
        //3.根据购销合同的id 查询所有购销合同
        ContractExample contractExample = new ContractExample();
        ContractExample.Criteria criteria = contractExample.createCriteria();
        criteria.andIdIn(Arrays.asList(ids));
        //将数组转换为list集合
        List<Contract> list = contractDao.selectByExample(contractExample);

        //4.拼接合同号集合的字符串
        String contractNos = "";
        for (Contract contract : list) {
            contractNos += contract.getContractNo()+ "";
            //修改合同状态 ： 将状态修改为已报运 2
            contract.setState(2);
            contractDao.updateByPrimaryKeySelective(contract);
        }
        export.setCustomerContract(contractNos);

        //II、保存报运单商品
        Map<String,String> map = new HashMap<>(); //货物id 和 商品id 之间的关系  hw02 -- sp02

        //1.根据合同id查询所有的货物
        ContractProductExample productExample = new ContractProductExample();
        ContractProductExample.Criteria productExampleCriteria = productExample.createCriteria();
        productExampleCriteria.andContractIdIn(Arrays.asList(ids));
        List<ContractProduct> contractProducts = contractProductDao.selectByExample(productExample);
        //2.循环所有的货物，创建报运单商品
        for (ContractProduct cp : contractProducts) {
            //3.设置商品id， 设置报运单的(id)外键 和其他数据
            ExportProduct ep = new ExportProduct();
          /*  exportProduct.setCnumber(cp.getCnumber());
            exportProduct.setPrice(cp.getPrice());*/
            BeanUtils.copyProperties(cp,ep);//将cp中的同名数据的数据 copy 到 ep中的同名属性上
            ep.setId(UUID.randomUUID().toString());
            ep.setExportId(export.getId());
            //4.保存报运单
            exportProductDao.insertSelective(ep);

            map.put(cp.getId(),ep.getId()); //将货物id作为键 ，商品id作为值
        }


        //III、保存报运单附件
        //1.根据合同id查询所有的合同附件
        ExtCproductExample example = new ExtCproductExample();
        ExtCproductExample.Criteria exampleCriteria = example.createCriteria();
        exampleCriteria.andContractIdIn(Arrays.asList(ids));
        List<ExtCproduct> extCproducts = extCproductDao.selectByExample(example);
        //2.循环所有的合同附件，创建报运单附件
        for (ExtCproduct extC : extCproducts) {
            ExtEproduct extE = new ExtEproduct();
            //3.设置普通属性
            BeanUtils.copyProperties(extC,extE);
            //4.设置id  报运单id  所属商品id
            extE.setId(UUID.randomUUID().toString());
            extE.setExportId(export.getId());
            //所属商品id （根据键 取出商品的值）
            String pid = map.get(extC.getContractProductId()); //hw02 货物id  -- 商品的id sp02
            extE.setExportProductId(pid); //设置商品id
            //5.保存报运单附件
            extEproductDao.insertSelective(extE);
        }

        //保存报运单
        export.setState(0);//设置草稿状态
        export.setProNum(contractProducts.size());
        export.setExtNum(extCproducts.size());
        exportDao.insertSelective(export);

    }

    //更新出口报运
    //update co_export_product where id = ?
    public void update(Export export) {
        //1.更新报运单
        exportDao.updateByPrimaryKeySelective(export);
        //2.更新报运单中的每一个商品数据
        if(export.getExportProducts() != null) {
            for (ExportProduct ep : export.getExportProducts()) {
                exportProductDao.updateByPrimaryKeySelective(ep);
            }
        }
    }

    //删除出口报运
    public void delete(String id) {

    }

    //根据id查询
    public Export findById(String id) {
        return exportDao.selectByPrimaryKey(id);
    }

    //分页查询
    public PageInfo findAll(ExportExample example, int page, int size) {
        //设置分页参数
        PageHelper.startPage(page,size);
        //查询全部
        List  list = exportDao.selectByExample(example);
        //构造返回值
        return new PageInfo(list);
    }

    //更新报运结果
    public void exportE(ExportResult result) {
         //1.更新报运单状态，更新报运单结果
        Export export = new Export();
        export.setId(result.getExportId());
        export.setState(result.getState());
        export.setRemark(result.getRemark());
        exportDao.updateByPrimaryKeySelective(export);

        //2.更新报运单商品的关税
        for (ExportProductResult epr : result.getProducts()) {
            ExportProduct ep = new ExportProduct();
            ep.setId(epr.getExportProductId());
            ep.setTax(epr.getTax());
            exportProductDao.updateByPrimaryKeySelective(ep);
        }

    }

}
